package com.jingzhi.huimiao.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import com.jingzhi.huimiao.MainActivity;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
 * 
 * 数据库的创建与版本管理的工具类
 * 
 * @author cxk
 *
 *
 */
public class DBHelper extends SQLiteOpenHelper {
	    
	    private Context mcontext;
		private static String DB_NAME;  
	        
	    public DBHelper(Context context,String databaseName,CursorFactory factory,int version) {    
	        //CursorFactory设置为null,使用默认值    
	        super(context, databaseName, factory, version);
	        mcontext = context;
	    }    
	    
	    
	    /**
		 * 数据库创建时调用
		 */
	    @Override    
	    public void onCreate(SQLiteDatabase db) {   
	    	//executeAssetsSQL方法用于向Assets文件夹对应得路径读取SQL语句然后执行创建操作
	        executeAssetsSQL(db, "word.sql");
	        Log.e("文件---------", "right1.db");
	        
	        System.out.println("创建表"); 
	    }    

		/**
		 * 数据库升级时调用
		 */
	    @Override    
	    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {    
	        if(newVersion <= oldVersion){
	        	return;
	        }
	        
	        Configuration.oldVersion = oldVersion;
	        
	        int changeCnt = newVersion - oldVersion;
	        for(int i=0; i<changeCnt; i++){
	        	String schemaName = "update" + (oldVersion + i ) + "_" + (oldVersion + i + 1) + ".sql";
	        	executeAssetsSQL(db, schemaName);
	        }
	    }    
	    
	    
	    /**
	     * 读取数据库文件（.sql）,并执行sql语句
	     * @param db
	     * @param string
	     */
	    private void executeAssetsSQL(SQLiteDatabase db, String schemaName) {
			BufferedReader bri = null;
			try {
				bri = new BufferedReader(new InputStreamReader(mcontext.getAssets().open(Configuration.DB_PATH+"/"+schemaName)));
				Log.e("路径---------", bri.toString());
				System.out.println("路径："+Configuration.DB_PATH+"/"+schemaName );
				
				String line;
				String buffer = "";
				while((line = bri.readLine())!= null){
					buffer += line;
					if(line.trim().endsWith(";")){
						db.execSQL(buffer.replace(";", ""));
						buffer = "";
					}
				}
			} catch (IOException e) {
				Log.e("db-error", e.toString());
			}finally{
				if(bri != null){
					try {
						bri.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			
		}
	    
	    public static String GetDataBasePath(Context context) {
	    	   
//	    	  String packageName = context.getPackageName();
	    	  //Log.i("PackName", packageName);
	    	  // String DB_PATH = String.format("/data/data/%1$s/databases/",
	    	  // packageName);
	    	  DB_NAME = "right1.db";
	    	  String DB_PATH = "/data/data/com.jingzhi.huimiao/databases/"+ DB_NAME;
	    	 
	    	  if ((new File(DB_PATH)).exists() == false) {
	    	   try {
	    	    // 如 SQLite 数据库文件不存在，再检查一下 database 目录是否存在
	    	    File f = new File(DB_PATH);
	    	    // 如 database 目录不存在，新建该目录
	    	    if (!f.exists()) {
	    	     f.mkdir();
	    	    }
	    	    // 得到 assets 目录下我们实现准备好的 SQLite 数据库作为输入流
	    	    InputStream is = context.getAssets().open(Configuration.DB_PATH+"/"+DB_NAME);
	    	    // 输出流
	    	    OutputStream os = new FileOutputStream(DB_PATH);
	    	    // 文件写入
	    	    byte[] buffer = new byte[1024];
	    	    int length;
	    	    while ((length = is.read(buffer)) > 0) {
	    	     os.write(buffer, 0, length);
	    	    }
	    	    // 关闭文件流
	    	    os.flush();
	    	    os.close();
	    	    is.close();
	    	   } catch (Exception e) {
	    	    e.printStackTrace();
	    	   }
	    	  }
	    	 
	    	  return DB_PATH;
	    	 }
}
